<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-form label-width="auto" style="max-width: 700px">
        <el-form-item>
          <el-input size="large" style="width: 500px" v-model="aab.query" placeholder="请输入内容" />
          <el-button :icon="Search" style="width: 50px" size="large"  @click="query"/>
          <el-button type="primary" size="large" class="box_button" @click="dialogFormVisible = true">添加用户</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="tableData" style="width: 100%" border stripe>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="username" label="姓名" width="180" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="mobile" label="电话" />
        <el-table-column prop="role_name" label="角色" />
        <el-table-column label="状态">
          <template v-slot="scope">
            <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button type="primary" circle size="large" :icon="EditPen" @click="getUseById(scope.row.id)"></el-button>
            <!--top 上 buttom下  left左 right右 start end  content 提示信息 -->
            <el-tooltip class="item" effect="light" content="删除角色" placement="top-start">
              <el-button type="danger" circle size="large" :icon="Delete" @click="delUseById(scope.row.id)"></el-button>
            </el-tooltip>

            <!-- el-tooltip鼠标悬浮 给提示 effect 显示的背景颜色 -->
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top">
              <el-button type="warning" circle size="large" :icon="Setting"
                @click="distributeRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- size-change	page-size 改变时触发   current-change	current-page 改变时触发  v-model:page-size	每页显示条目个数  v-model:current-page	当前页数-->
      <el-pagination v-model:current-page="aab.pagenum" v-model:page-size="aab.pagesize" :page-sizes="[1, 3, 5, 10]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange"></el-pagination>
    </el-card>
    <!-- 添加用户 -->
    <el-dialog :destroy-on-close="true" v-model="dialogFormVisible" title="添加用户" width="50%" @closed="resetUser">
      <el-form :model="userform" :rules="ruleform" ref="userformRef">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input size="large" v-model="userform.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input size="large" v-model="userform.password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input size="large" v-model="userform.email" autocomplete="off" />
        </el-form-item>
        <el-form-item label="手机" :label-width="formLabelWidth" prop="mobile">
          <el-input size="large" v-model="userform.mobile" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="submitForm">确定</el-button>
          <el-button type="primary" @click="dialogFormVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 修改用户 -->
    <el-dialog :destroy-on-close="true" v-model="dialogFormVisible1" title="修改用户" width="50%" @closed="resetUser">
      <el-form :model="userform" ref="userUpdataformRef" :rules="ruleform">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input disabled v-model="userform.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="userform.email" autocomplete="off" type="email" />
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="userform.mobile" autocomplete="off" type="tel" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="updateUser">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog :destroy-on-close="true" v-model="centerDialogVisibleRole" title="分配角色" width="50%" @closed="resetUser">
      <el-row>
        <el-col :span="3" class="col-rigth">当前用户:</el-col>
        <el-col :span="21">{{ userRow.value.username }}</el-col>
      </el-row>
      <el-row>
        <el-col :span="3" class="col-rigth">当前角色:</el-col>
        <el-col :span="20">{{ userRow.value.role_name }}</el-col>
      </el-row>
      <el-row>
        <el-col :span="3" class="col-rigth">分配角色:</el-col>
        <el-col :span="20">
          <el-select v-model="role_id" placeholder="选择角色">
            <el-option v-for="(item, index) in roleList" :key="index" :label="item.roleName"
              :value="item.id"></el-option>
          </el-select>
        </el-col>
      </el-row>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="usersIdRole">确定</el-button>
          <el-button @click="centerDialogVisibleRole = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { Search, Setting, EditPen, Delete } from '@element-plus/icons-vue'
import request from '@/util/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { userp, responseUserData } from '@/api/user/type'
let dialogFormVisible = ref(false)
let userRow = {}
let roleList = ref([])
let dialogFormVisible1 = ref(false)
let centerDialogVisibleRole = ref(false)
let role_id = ref('')
const formLabelWidth = '80px'
const tableData = ref<userp[]>([])
const aab = ref({
  query: '',
  pagenum: 1,
  pagesize: 3,
})
const total = ref(0)
const userformRef = ref({})
const userUpdataformRef = ref({})
const userform = ref({
  username: '',
  password: '',
  email: '',
  mobile: '',
})
const userform1 = ref({
  username: '',
  password: '',
  email: '',
  mobile: '',
})
const getMenu = async () => {
  const { data } = await request({
    url: `/users`,
    method: 'GET',
    params: aab.value,
  })
  tableData.value = data.users
  total.value = data.total
}
// 表单校验
const ruleform = {
  username: [
    // required必填项,不能是空 message 错误信息 trigger 触发条件
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入qq邮箱', trigger: 'blur' },
    { pattern: /^\w+(?:\.[_a-zA-Z0-9-]+)*@\w*qq.com$/, message: '请输入qq邮箱', trigger: 'blur' },
  ],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[34578]\d{9}/, message: '请输入正确手机号', trigger: 'blur' },
  ],
}
const submitForm = () => {
  userformRef.value.validate(async (istrue: any) => {
    // 如果是true 代表校验成功
    if (!istrue) {
      return ElMessage.error('请正确填写表单')
    }
    // response的类型
    const { meta }: responseUserData = await request({
      url: '/users',
      method: 'POST',
      data: userform.value,
    })
    if (meta.status !== 201) {
      if (meta.status !== 400) {
        return ElMessage.error('网络异常,稍后重试')
      }
      return ElMessage.error(meta.msg)
    }
    ElMessage.success('添加成功')
    dialogFormVisible.value = false
    userform.value = '' as any
    getMenu()
  })
}
const handleSizeChange = (size: any) => {
  aab.value.pagesize = size
  getMenu()
}
const handleCurrentChange = (page: any) => {
  aab.value.pagenum = page
  getMenu()
}
const query = () => {
  // 每次搜索,页数从1开始
  aab.value.pagenum = 1
  getMenu()
}
onMounted(() => {
  getMenu()
})
// 修改角色
const getUseById = async (id) => {
  const { data, meta }: responseUserData = await request({
    url: `/users/${id}`,
    method: 'GET',
  })
  // console.log(data, meta);
  // 获取数据失败
  if (meta.status !== 200) {
    return ElMessage.error('网络异常,稍后重试')
  }
  // 成功,将后台的数据,付给userform,将id附上了
  Object.assign(userform.value, data)
  // console.log(this.userform);
  // 显示对话框
  dialogFormVisible1.value = true
}
const updateUser = () => {
  userUpdataformRef.value.validate(async (valid) => {
    // console.log(valid);
    // 校验没有通过
    if (!valid) {
      return ElMessage.error('填写正确数据')
    }
    // 使用包装过的axios,request
    const { data, meta }: responseUserData = await request({
      // 少id
      url: `/users/${userform.value.id}`,
      method: 'PUT',
      data: userform.value,
    })
    // 获取数据失败
    if (meta.status !== 200) {
      return ElMessage.error('网络异常,稍后重试')
    }
    // 先关闭,在便利
    ElMessage.success('修改成功')
    dialogFormVisible1.value = false
    // 重新便利
    getMenu()
  })
}
// 删除角色
const delUseById = async (id) => {
  try {
    await ElMessageBox.confirm('是否删除数据?', '危险', {
      confirmButtonText: '是',
      cancelButtonText: '否',
      type: 'error',
    })
    const { meta }: responseUserData = await request({
      url: `/users/${id}`,
      method: 'DELETE',
    })
    // console.log(data, meta);
    // 获取数据失败
    if (meta.status !== 200) {
      return ElMessage.error('网络异常,稍后重试')
    }
    // 页数> 1 并数据只有1条 跳转到上一页
    if (aab.value.pagenum > 1 && tableData.value.length === 1) {
      aab.value.pagenum = aab.value.pagenum - 1
    }
    // 刷新数据
    getMenu()
    return ElMessage.success(meta.msg)
  } catch (error) {
    // console.log("error---->", error);
    return ElMessage.info('已经取消')
  }
}
// 分配角色
let distributeRole = async (user: any) => {
  // 显示分配角色的对话框
  centerDialogVisibleRole.value = true
  userRow.value = user
  // 获取到所有角色
  const { data, meta }: responseUserData = await request({
    url: '/roles',
    method: 'GET',
  })
  if (meta.status !== 200) {
    return ElMessage.error('获取数据失败')
  }
  roleList.value = data
  getMenu()
}

let usersIdRole = async () => {
  const { meta }: responseUserData = await request({
    url: `users/${userRow.value.id}/role`,
    data: { rid: role_id.value },
    method: 'PUT',
  })
  if (meta.status !== 200) {
    return ElMessage.error('网络异常,稍后重试')
  }
  // 关闭对话框
  centerDialogVisibleRole.value = false
  // 重新遍历用户信息
  role_id.value = ''
  ElMessage.success('分配成功')
  getMenu()
}
// 数据重置
let resetUser = () => {
  Object.assign(userform.value, userform1.value)
}
</script>

<style scoped>
.el-card {
  margin-top: 20px;
}

.box_button {
  margin-left: 30px;
}

.el-pagination {
  margin-top: 10px;
}

.el-col {
  margin-top: 10px;
}
</style>
